Completed
Push — master ( f991c2...b8dc7c )
by Andres
38s
created

angular.service(ꞌsavegameꞌ)   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
c 2
b 0
f 0
nc 1
dl 0
loc 3
rs 10
nop 0
1
/* globals versionCompare, atob, btoa */
2
'use strict';
3
4
angular
5
  .module('game')
6
  .service('savegame', ['$state',
7
    'state',
8
    'data',
9
    function ($state, state, data) {
10
      this.initSave = function () {
11
        state.player = {};
12
        this.versionControl();
13
        state.init();
14
        $state.go('matter');
15
      };
16
17
      this.save = function () {
18
        localStorage.setItem('player', JSON.stringify(state.player));
19
      }
20
21
      this.load = function () {
22
        try {
23
          let storedPlayer = localStorage.getItem('player');
24
          if (!storedPlayer) {
25
            this.initSave();
26
          } else {
27
            state.player = JSON.parse(storedPlayer);
28
            this.versionControl();
29
          }
30
        } catch (err) {
31
          alert('Error loading savegame, reset forced.');
32
          this.initSave();
33
        }
34
      };
35
36
      this.versionControl = function () {
37
        // delete saves older than this version
38
        if (state.player.version && versionCompare(state.player.version, '2.1.0') < 0) {
39
          state.player = {};
40
        }
41
        // we merge the properties of the player with the start player to
42
        // avoid undefined errors with new properties
43
        state.player = angular.merge({}, data.start_player, state.player);
44
        // append an id if it doesn't exist
45
        if (!state.player.id) {
46
          state.player.id = Math.random().toString().substring(3);
47
        }
48
      }
49
    }
50
  ]);
51